package servlet;

import service.UserService;
import userDao.Student;
import userDao.User;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "AdminLogin",urlPatterns = "/login")
public class AdminLogin extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        System.out.println("账户：" + userName + " " + "密码：" + password );
        UserService userService = new UserService();
        User user = userService.getUser(new User(userName, password));
        if (null == user){
            System.out.println("登录失败");
            request.setAttribute("error","用户名或密码错误！");
            RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
            rd.forward(request,response);
        }else {
            System.out.println("登录成功！");
            request.getSession().setAttribute("user",user);
            List<Student> students = userService.getStudents();
            request.getSession().setAttribute("students",students);
            RequestDispatcher rd = request.getRequestDispatcher("studentManage.jsp");
            rd.forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       this.doPost(request, response);
    }
}
